import thin_render from "./thin_render.mjs";
import { after, clearafterqueue } from "./delay_render.mjs";
import { nearest_data } from "./nearest.mjs";
import { thin } from "../thin3.mjs";

export default function (container, template) {
  // console.log({ container, template });
  let element = document.createElement("route");
  container.append(element);
  element.thin_route = template;

  after(render);

  if (!nearest_route(container)) {
    // 只给在首次使用route时绑定侦听事件。
    window.addEventListener("popstate", (e) => {
      // console.log(e);
      render();
      clearafterqueue();
    });
  }

  function nearest_route(node) {
    while (node && node.nodeName.toUpperCase() !== "ROUTE") {
      node = node.parentNode;
    }
    return node;
  }

  function render() {
    // console.log("render");
    thin(element).empty();
    let currenthashpath = document.location.hash;

    // console.log({ routes: template.route });
    let routes = Object.keys(template.route);
    for (let i = 0; i < routes.length; i++) {
      let route = routes[i];
      // console.log({ route });

      let param;

      let regstr = route.replace(/:\w+/g, (m) => {
        if (!param) param = {};
        param[m.slice(1)] = undefined;
        // console.log({ m: m.slice(1), param });
        return "(\\w+)";
      });

      let reg = new RegExp("^".concat(regstr, "(/|$)"));
      let matchs = currenthashpath.match(reg);
      // console.log({ matchs });
      if (matchs) {
        if (matchs.length > 2) {
          for (i = 1; i < matchs.length - 1; i++) {
            // 第一个match是全模式，最后一个匹配尾部，都要排除，中间的才是路径变量
            param[Object.keys(param)[i - 1]] = matchs[i];
          }
          element.thin_param = param;
        }
        // console.log({ element, template: template.route[route], route });
        // thin.after(() => {
        thin_render(element, template.route[route] || "");
        // });
        return;
      }
    }

    // 渲染默认模板
    if (template.default) thin_render(element, template.default);
  }
}
